import router from './index'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'
import { generateRoutes } from './utils'

const whiteList = ['/login', '/404', '/401'] // 白名单

// 用于标记路由是否已经动态添加
let hasAddRoutes = false

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  const { token, userInfo, menuList } = storeToRefs(userStore)
  // console.log('路由守卫 token:', token.value)
  // console.log('路由守卫 userInfo:', userInfo.value)

  if (token.value) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 如果没有路由，但有用户信息，直接生成路由
      if (!hasAddRoutes) {
        if (userInfo.value && menuList.value.length) {
          // 使用本地存储的数据生成路由
          const accessRoutes = generateRoutes(menuList.value)
          
          accessRoutes.forEach(route => {
            router.addRoute(route as any)
          })
          router.addRoute({
            path: '/:pathMatch(.*)*',
            redirect: '/404'
          })
          hasAddRoutes = true
          next({ ...to, replace: true })
        } else {
          try {
            // 获取用户信息
            const hasInfo = await userStore.getInfo()
            console.log('路由守卫获取用户信息结果:', hasInfo)
            console.log('路由守卫更新后的用户信息:', userStore.userInfo)
            if (hasInfo) {
              // 生成动态路由
              const accessRoutes = generateRoutes(menuList.value)
              
              // 添加动态路由
              accessRoutes.forEach(route => {
                router.addRoute(route as any)
              })

              // 添加404路由
              router.addRoute({
                path: '/:pathMatch(.*)*',
                redirect: '/404'
              })

              

              // 标记路由已添加
              hasAddRoutes = true

              // 重定向到目标路由
              next({ ...to, replace: true })
            } else {
              userStore.clearAll()
              hasAddRoutes = false
              next('/login')
            }
          } catch (error) {
            userStore.clearAll()
            hasAddRoutes = false
            next('/login')
          }
        }
      } else {
        console.log("router:", router);
        next()
      }
    }
  } else {
    hasAddRoutes = false
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
}) 